package com.queue;


import java.util.Scanner;

/**
 * @author 江岸
 * @version V1.0
 * @ClassName: ArrayQueueDemo
 * @description: 使用环形数组模拟队列
 * @date 2020/9/1620:00
 * @since V1.0
 */
public class ArrayQueueDemo {
    public static void main(String[] args) {
        boolean flag = true;
        CircleArray queue = new CircleArray(5);
        Scanner scanner = new Scanner(System.in);
        while (flag) {
            System.out.println("请输入你的选择:1.show(s) 2.add(a) 3.get(g) 4.head(h) 5.exit(e)");
            char next = scanner.next().charAt(0);
            switch (next){
                case 's':
                    queue.show();
                    break;
                case 'a':
                    System.out.println("输入数字");
                    int i = scanner.nextInt();
                    queue.add(i);
                    break;
                case 'g':
                    try {
                        int x = queue.get();
                        System.out.printf("取值:%d",x);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    queue.head();
                    break;
                case 'e':
                    flag = false;
                    break;
                default:
                    break;
            }
        }
    }
}

class CircleArray {
    private int size;//数组最大容量
    private int front;//队列的第一个值，初始值0
    private int end;//指向队列最后一个元素后面的一位，因为希望空出来一个位置做处理 初始值0
    private int[] arr;

    public CircleArray(int n) {
        size = n;
        arr = new int[size];
    }

    public boolean isFull() {
        return (end + 1) % size == front;
    }

    public boolean isEmpty() {
        return end == front;
    }

    public void show() {
        if (isEmpty()) {
            System.out.println("队列中没有元素，无法遍历");
            return;
        }
        System.out.println("遍历队列元素");
        for (int i = 0; i < (end + size - front) % size; i++) {
            System.out.printf("arr[%d]=%d,", (i + front) % size, arr[(i + front) % size]);
        }
    }

    public void head() {
        if (isEmpty()) {
            System.out.println("队列中没有元素，无法遍历");
            return;
        }
        System.out.printf("头部元素为：arr[%d]=%d", front, front);
    }

    public void add(int a) {
        if (isFull()) {
            System.out.println("队列已经满了，无法新增");
            return;
        }
        arr[end] = a;
        end = (end + 1) % size;
    }

    public int get() {
        if (isEmpty()) {
            throw new RuntimeException("队列中没有元素，无法取值");
        }
        int num = arr[front];
        front = (front + 1) % size;
        return num;
    }
}

